package com.aim.util.filters;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
 * User: Avraham Shvartzon
 * Date: 9/12/14
 */
public abstract class ChainFilter<T> implements Filter<T> {

    protected String name;
    protected List<ChainFilter<T>> nextFilter;

    public ChainFilter(String name) {
        this(name, null);
    }

    public ChainFilter(String name, List<ChainFilter<T>> nextFilter) {
        this.name = name;
        this.nextFilter = nextFilter;
    }

    @Override
    public boolean accept(T t) {
        if (nextFilter == null || nextFilter.isEmpty()){
            return true;
        }
        for (ChainFilter<T> filter : nextFilter) {
            if (filter.accept(t) == false){
                return false;
            }
        }

        return true;
    }

    public String getName(){
        String s = name;
        if (nextFilter != null){
            for (ChainFilter<T> filter : nextFilter) {
                s += filter.getName() + " + ";
            }
            s = s.substring(0, s.length()-2);
        }
        return s;
    }



    public static <T> ChainFilter<T> createFilter(ChainFilter<T>... filters){
        return new ChainFilter<T>("", Arrays.asList(filters)){};

    }
}
